/***********************************************************************
 * @package：，@class-name：DBPool.java
 * @creator Administrator
 * @create-time 2016年1月28日 上午10:50:36
 * @revision $Id: 1.0
 ***********************************************************************/
package cn.wj.base.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class DBPool{
	
	private  PropertiesLoader ploader=null;
	private  Connection connection=null;
	private  BlockingQueue<Connection> connList=null;
	private  int minpool;
	private  int maxpool;
	private  int poolsize;
	
	private static class LazyHolder{
		private static final DBPool db=new DBPool();
	}
	
	private DBPool(){
		ploader=PropertiesLoader.getInstance();
		minpool=ploader.getMinPool();
		maxpool=ploader.getMAXPool();
		initPool();
	}
	
	public static final DBPool getInstance(){
		return LazyHolder.db;
	}
	
	//初始化
	 private void initPool(){
		connList=new LinkedBlockingQueue<Connection>();
		for (int i = 0; i < minpool; i++) {
			try {
				connList.put(addConnection());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		poolsize=minpool;
	 }
	 
	 //释放连接
	 public  void releaseConnection(Connection conn){
		 try {
			 connList.put(conn);
		 } catch (InterruptedException e) {
			 e.printStackTrace();
		 }
	 }
	 
	 //添加连接 
	private Connection addConnection(){
		try {
			Class.forName(ploader.dbClass());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
		 for(int i=0;i<minpool;i++){
			 connection = DriverManager.getConnection(ploader.dbUrl(), ploader.dbUser(),ploader.dbPassword());
		 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	
	//获取连接
	public  Connection getConnection(){
		Connection conn=null;
		if(connList.size()>0){
			try {
				conn= connList.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			//1.连接池有没有达到最大
			if(poolsize<maxpool){
				for(int i=0;i<( maxpool-poolsize);i++ ){
					connList.add(addConnection());
				}
				poolsize=maxpool;
			}
			//2.返回连接
			try {
				conn= connList.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return conn;
	
} 
}